//////////////////////注册
//判断是否在微信打开
var isweixin="";
function is_weixn(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
if(is_weixn()){
    isweixin="/weixin/";//原始跳转页面
}
//判断PC
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var IsPC=true;
for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) { IsPC=false; break; }
}

var clocktim=60;//读秒
var phonenumber;
var username;
var password;
var tohrefurl=isweixin+"pulu.html";//原始跳转页面
var fromuser="";
var zctype=1;//默认为普通注册
//cookie保存数据 用于登录页面
var loca=location.href;
function getFromUser(){
    if(loca.match(/fromuser=[a-z0-9]+/)){
        fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
        if(!/[0-9]/.test(fromuser)){fromuser=""}
    }else{
        if($.cookie("fromuser")&&/[0-9]/.test($.cookie("fromuser"))){
            fromuser=$.cookie("fromuser");
        }
    }
}
if(/newsid=/.test(loca)){
    var newsid=loca.match(/newsid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",newsid);
        zctype=2;
    }
}else if(/qid=/.test(loca)){
    var qid=loca.match(/qid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",qid);
        zctype=2;
    }
}else if(/eid=/.test(loca)){
    var eid=loca.match(/eid=[0-9]+/)[0];
    getFromUser();
    if(fromuser&&/[0-9]/.test(fromuser)){
        $.cookie("fromuser",fromuser);
        $.cookie("fromid",eid);
        zctype=2;
    }
}
//扫码加好友
if(/index.html#fromuser=[0-9a-z]+/.test(location.href)){
    fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
    if(/[0-9]/.test(fromuser)){$.cookie("fromuser",fromuser);}
}
//从登录页面过来
if(document.referrer.match(/login/)){
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
}else if(document.referrer.match(/weixinsharenews/)||document.referrer.match(/questiondetail/)||document.referrer.match(/shareexppage/)||document.referrer.match(/newsdetail/)||document.referrer.match(/pulunews_share/)){
    //从详情页进来快速注册
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
    $("#register .text_note").html("无需下载，快速注册，查看精彩内容");
}else{

}
//微信关注公众号
function focusWX(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.ajax({
        type:"get",
        url:harassurl+md5phonenumber,
        success:function(d){
            //没有关注
            if(!d.Data){
                $("#harass").css("display","block");
            }
            //已经关注 红包图
            else{
                $("#finishnotic").css("display","block");
            }
        }
    });
}
//关闭微信关注弹框
$("#closeharass").click(function(){
    $("#harass").css("display","none");
    $("#finishnotic").css("display","block");
});
$("#closeharass1").click(function(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.ajax({
        type:"post",
        url:changeqrurl,
        data:{"userId":md5phonenumber},
        success:function(d){
            $("#harass").css("display","none");
            $("#finishnotic").css("display","block");
        }
    })
});
//展开注册
$("#registerbtn").click(function(){
    location.href+="#register";
    $("#register").css("display","block");
    $(".pagedlist_item").css("display","none");
});
//关闭注册
$("#registerback").click(function(){
    if(document.referrer.match(/login/)){
        history.go(-1);
    }else{
        history.go(-1);
        $("#register").css("display","none");
        $(".pagedlist_item").css("display","block");
    }
});
//物理返回操作
if( ("onhashchange" in window) && ((typeof document.documentMode==="undefined") || document.documentMode==8)) {
    //浏览器支持onhashchange事件
    window.onhashchange = hashChangeFire;
} else { // 不支持则用定时器检测的办法
    setInterval(function() {
        var ischanged = isHashChanged();
        if(ischanged) {
            hashChangeFire();
        }
    }, 150);
}
function hashChangeFire(){
    if(!/register/.test(location.href)){
        $("#register").css("display","none");
        $(".pagedlist_item").css("display","block");
    }
}
//验证码
var yanzhengma="yes";//验证码可以点击 控制点击一次
$("#timclock").click(function(){
    //alert("执行");
    $("#tishiinfor").html("");
    phonenumber=$("#phonenumber").val();
    username=$("#username").val();
    password=$("#password").val();
    reg=/0?(13|14|15|18)[0-9]{9}$/;
    if(!reg.test(phonenumber)){
        $("#tishiinfor").html("请输入正确的手机号！")
    }else if($("#username").val()===""||username.match(/\s/)){
        $("#tishiinfor").html("昵称格式有误！");
        console.log("昵称长度："+username.length);
    }else if(!(/[0-9]{6,12}|[a-z]{6,12}|[A-Z]{6,12}|[0-9a-zA-Z]{6,12}/.test(password))||password.length<6||password.length>12){
        $("#tishiinfor").html("密码不符合规范！");
        console.log(password.length);
        console.log("昵称长度："+username.length);
    }else{
        //判断是否已经存在
        var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
        if(yanzhengma==="yes"){
            yanzhengma="no";//验证码当前不能点击
            $("#timclock").html(60);
            var secondtime=setInterval(function(){
                if(clocktim>0){
                    clocktim--;
                    $("#timclock").html(clocktim);
                }else{
                    clearInterval(secondtime);
                    $("#timclock").html("获取验证码");
                    clocktim=60;
                    yanzhengma="yes";//验证码可以点击
                }
            },1000);

            //发送验证码
            $.ajax({
                type:"get",
                dataType: "json",
                url:"https://www.pulu.com/webapi/api/Sms/GetValidCode?phoneNum="+$("#phonenumber").val(),
                success:function(data){
                    console.log(data);
                    if(data.Code==="FALSE"){
                        if(data.Message.match(/a-z/)){
                            $("#tishiinfor").html("验证码获取失败，请稍后再试。");
                        }else if(data.Message.match(/5/)){
                            $("#tishiinfor").html("已经超过当天请求5次限制");
                        }
                    }else{

                    }
                }
            });

        }
    }
});
//注册按钮
$("#nextstep").click(function(){
    //注册中包含短信验证
    $("#tishiinfor").html("");
    phonenumber=$("#phonenumber").val();
    var username=$("#username").val();
    password=$("#password").val();
    reg=/0?(13|14|15|18)[0-9]{9}$/;
    if(!reg.test(phonenumber)){
        $("#tishiinfor").html("请输入正确的手机号！")
    }else if(!/^([\u4e00-\u9fa5]{1,7}|[a-zA-Z\.\s]{1,7})$/.test($("#realname").val())){
        $("#tishiinfor").html("姓名不符合规范！");
    }else if(!/^[\u4E00-\u9FA5a-zA-Z0-9_]{1,7}$/.test($("#username").val())){
        $("#tishiinfor").html("昵称仅支持中英文、数字和下划线！");
    }else if(!(/[0-9]{6,12}|[a-z]{6,12}|[A-Z]{6,12}|[0-9a-zA-Z]{6,12}/.test(password))){
        $("#tishiinfor").html("密码不符合规范！");
    }else if(/cannot/.test($("#nextstep").attr("class"))){
        $("#tishiinfor").html("您尚未选择订阅号！");
    }else if(!/[0-9]+/.test($("#phonetestinput").val())){
        $("#tishiinfor").html("请输入验证码!");
    }else{
        var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
        var md5password=hex_md5(password).substring(7, 23);
        $("#tishiinfor").html("正在注册...");
        //获取新闻类别
        var jobids=[],hobbyids=[],newsids=[];
        $(".newsname span").each(function(){
            var num=this.id.match(/[0-9]+/)[0];
            if(this.dataset.type==190){
                newsids.push(num);
            }else if(this.dataset.type==191){
                jobids.push(num);
            }else if(this.dataset.type==192){
                hobbyids.push(num);
            }
        });
        //加好友
        var fromuser="";
        var loca=location.href;
        if(loca.match(/fromuser=[a-z0-9]+/)){
            fromuser=loca.match(/fromuser=[a-z0-9]+/)[0].split("=")[1];
            if(/[0-9]/.test(fromuser)){
                zctype=2;
                $.cookie("shareUserId",fromuser);//保存回答转发者
            }
        }else if($.cookie("fromuser")&&/[0-9]/.test($.cookie("fromuser"))){
            fromuser=$.cookie("fromuser");
            zctype=2;
            $.cookie("shareUserId",fromuser);//保存回答转发者
        }
        $.ajax({
            type:"post",
            dataType: "json",
            url:"https://www.pulu.com/webapi/api/PuluUser/Register",
            data:{"userId":md5phonenumber,"userNick":username,"userPhone":phonenumber,"password":md5password,"type":zctype,"verification_code":$("#phonetestinput").val(),"fromUserId":fromuser,"newsids":newsids,"jobids":jobids,"hobbyids":hobbyids,"realName":$("#realname").val()},
            success:function(data){
                if(fromuser){console.log(fromuser);}
                else{console.log("没有");}
                if(data.Data==1){ //注册成功
                    //保存信息
                    $.cookie("MYID",hex_md5(phonenumber).substring(7, 23));
                    console.log($.cookie("MYID"));
                    $.cookie("MYAVA","");
                    $.cookie("MYNICK",$("#username").val());
                    $("#tishiinfor").html("");
                    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
                    var md5password=hex_md5(password).substring(7, 23);
                    var username=$("#username").val();
                    //    环信创建链接
                    var conn = new WebIM.connection({
                        https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
                        url: WebIM.config.xmppURL,
                        isAutoLogin: WebIM.config.isAutoLogin,
                        isMultiLoginSessions: WebIM.config.isMultiLoginSessions
                    });
                    //注册环信
                    var options = {
                        username: md5phonenumber,
                        password: md5phonenumber,
                        nickname: username,
                        appKey: "pulu#pulu",
                        success: function (d) {
                            console.log("成功");
                            console.log(d)
                        },
                        error: function (d) {},
                        apiUrl: WebIM.config.apiURL
                    };
                    WebIM.utils.registerUser(options);
                    //微信openid
                    if($.cookie("wxopenid")){
                        $.ajax({
                            type:"post",
                            url:"https://www.pulu.com/webapi/api/WebChatInfo/AddWebChatInfo",
                            data:{"userId":md5phonenumber,"webchatId":$.cookie("wxopenid")},
                            success:function(d){
                                //红包 联系人
                                if(!fromuser){ //联系人
                                    $("#register").css("display","none");
                                    //没有推荐人 不弹红包图 填写推荐人
                                    $("#fromUserPhone").css("display","block");
                                }else{  //红包
                                    //有推荐人 红包 关注判断
                                    if(is_weixn()){
                                        focusWX("finishnotic");
                                    }else{
                                        $("#finishnotic").css("display","block");
                                    }

                                }
                            }
                        })
                    }
                    else{
                        //如果是从转发页面过来的将自己的数据拼接进去
                        var loca=location.href;
                        if(/newsid=/.test(loca)){
                            var newsid=loca.match(/newsid=[0-9]+/)[0].match(/[0-9]+/)[0];
                            tohrefurl=isweixin+"newsdetail.html?newsid="+newsid+"#fromuser="+md5phonenumber;
                        }
                        else if(/qid=/.test(loca)){
                            var qid=loca.match(/qid=[0-9]+/)[0].match(/[0-9]+/)[0];
                            tohrefurl=isweixin+"questiondetail.html?qid="+qid+"#fromuser="+md5phonenumber;
                        }
                        else if(/eid=/.test(loca)){
                            var eid=loca.match(/eid=[0-9]+/)[0].match(/[0-9]+/)[0];
                            tohrefurl=isweixin+"shareexppage.html?eid="+eid+"#fromuser="+md5phonenumber;
                        }
                        //红包 联系人
                        if(!fromuser){
                            $("#register").css("display","none");
                            $("#fromUserPhone").css("display","block");
                        }else{
                            $("#finishnotic").css("display","block");
                        }
                    }
                }else if(data.Data==2){
                    $("#tishiinfor").html("该帐号已被注册！");
                }else if(data.Data==3){
                    $("#tishiinfor").html("验证码错误!");
                }else if(data.Data==4){
                    $("#tishiinfor").html("用户昵称已经存在!");
                }
            }
        });
    }
});
//邀请人
$("#fromUserPhoneBtn").click(function(){
    $("#fromUserPhoneError").html("PULU账号不存在");
    $("#fromUserPhoneError").css("display","none");
    $("#fromUserPhoneNote").css("display","block");
    if($("#fromphonenumber").val()){
        console.log("有内容");
        var reg=/0?(13|14|15|18)[0-9]{9}$/;
        if(!reg.test($("#fromphonenumber").val())){
            $("#fromUserPhoneError").html("手机号格式错误！");
            $("#fromUserPhoneError").css("display","block");
            $("#fromUserPhoneNote").css("display","none");
        }
        else{
            console.log("手机号正确,搜索好友");
            $.ajax({
                datatype: "json",
                type: "get",
                url: searchfriendurl+"?userId="+$.cookie("MYID")+"&nick="+$("#fromphonenumber").val(),
                success: function (data) {
                    console.log(data);
                    if(data.Data&&data.Data.length>0){
                        var searchUser=data.Data[0].userId;
                        console.log(searchUser);
                        //加好友
                        $.ajax({
                            type:"post",
                            datatype:"json",
                            url:"https://www.pulu.com/webapi/api/PuluGoodFriend/Addpulu_goodfriend",
                            data:{"userId":$.cookie("MYID"),"friendId":searchUser},
                            success:function(d){
                                if(d.Message==="不能加自己为好友"){
                                    $("#fromUserPhoneError").html("不能加自己为好友！");
                                    $("#fromUserPhoneError").css("display","block");
                                    $("#fromUserPhoneNote").css("display","none");
                                }
                                else{
                                    //关注判断
                                    if(is_weixn()){
                                        focusWX();
                                    }else{ //红包
                                        $("#finishnotic").css("display","block");
                                    }
                                }
                            }
                        });
                    }
                    else{
                        $("#fromUserPhoneError").css("display","block");
                        $("#fromUserPhoneNote").css("display","none");
                    }
                }
            })
        }
    }
    else{
        console.log("没有内容直接登录");
        $("#finishnotic").css("display","block");
    }
});
//注册完 点击红包
$("#redbox").click(function(){
    phonenumber=$("#phonenumber").val();
    var md5phonenumber=hex_md5(phonenumber).substring(7, 23);
    $.cookie("MYID",md5phonenumber);
    var loca=location.href;
    if(/newsid=/.test(loca)){
        var newsid=loca.match(/newsid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"newsdetail.html?newsid="+newsid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    else if(/qid=/.test(loca)){
        var qid=loca.match(/qid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"questiondetail.html?qid="+qid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    else if(/eid=/.test(loca)){
        var eid=loca.match(/eid=[0-9]+/)[0].match(/[0-9]+/)[0];
        tohrefurl=isweixin+"shareexppage.html?eid="+eid+"#fromuser="+$.cookie("MYID");
        $.cookie("tohrefurl",tohrefurl);//用户选择类别后最终跳转地址
    }
    location.href=tohrefurl;
});
$('input').bind('input propertychange', function() {
    $("#tishiinfor").html("");
    $("#timplace").css("display","block");
    $("#othernote").html("");
    $("#othernote").css("display","none");
});